package com.orange.notificationsummary.event.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;

import com.orange.notificationsummary.R;
import com.orange.notificationsummary.event.pil.defaultimpl.BaseEvent;
import com.orange.notificationsummary.event.pil.defaultimpl.VoicemailEvent;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.Constants.EventType;
import com.orange.notificationsummary.utils.EventLSWidgetUtils;
import com.orange.notificationsummary.utils.LogHelper;
import com.orange.notificationsummary.utils.VipUtils;

public class VoiceMailDBHelper {
	private static final String	TAG				= "VoicemailDBHelper";

	public static final Uri		URI_VOICE_MAIL	= Uri.parse("content://com.orange.vvm.service.provider/message");
	private static final String	COLUMN_STATUS	= "status";

	public static Cursor getVoiceMailCursor(Context context) {
		Cursor cursor = null;
		if (EventLSWidgetUtils.isPackageExist(context,
						Constants.PKG_VOICEMAIL)
				&& EventLSWidgetUtils.getNotifictionTypesIsChecked(context,
						Constants.KEY_WIDGET_EVENT_DETAIL_VOICEMAIL)) {
			try {
				cursor = context.getContentResolver().query(URI_VOICE_MAIL,
						null, null, new String[] { "unread" }, "date");
			} catch (Exception e) {
			}
		}

		return cursor;
	}

	/**
	 * get voice mail info count
	 * 
	 * @return
	 */
	public static int getVoiceMailInfoCount(Context context) {
		Cursor c = null;
		int count = 0;
		try {
			c = context.getContentResolver().query(URI_VOICE_MAIL, null, null,
					new String[] { "unread" }, null);
			if (c != null && c.moveToFirst()) {
				do {
					++count;
				} while (c.moveToNext());
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "getVoiceMailInfoCount. ", e);
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return count;
	}

	/**
	 * get voice mail info list
	 */
	public static List<BaseEvent> getVoiceMailInfo(Context context) {
		List<BaseEvent> voicemailEvents = null;
		if (EventLSWidgetUtils.isPackageExist(context,
				Constants.PKG_NOTIFICATION_SUMMARY)
				&& EventLSWidgetUtils.getNotifictionTypesIsChecked(context,
						Constants.KEY_WIDGET_EVENT_DETAIL_VOICEMAIL)) {
			Cursor c = null;
			Map<String, Bitmap> contactPhotoMap = new HashMap<String, Bitmap>();
			Map<String, String> contactDisplayNameMap = new HashMap<String, String>();
			Map<String, String> numberTypeMap = new HashMap<String, String>();
			Map<String, Integer> numberCountMap = new HashMap<String, Integer>();

			try {
				c = context.getContentResolver().query(URI_VOICE_MAIL, null,
						null, new String[] { "unread" }, null);
				if (c != null && c.moveToFirst()) {
					voicemailEvents = new ArrayList<BaseEvent>();
					String voicemail_event_name = context.getResources()
							.getString(R.string.unread_voicemail_name);
					Drawable icon_voicemail_24 = context.getResources()
							.getDrawable(R.drawable.icon_voicemail_24);
					while (!c.isAfterLast()) {
						BaseEvent vmInfo = new VoicemailEvent(context);
						vmInfo.id = c.getInt(c.getColumnIndex("_id"));
						vmInfo.evnet_number = c.getString(c
								.getColumnIndex("fromNumber"));
						vmInfo.event_date = c.getLong(c.getColumnIndex("date"));
						LogHelper.v(TAG, "getVoiceMailInfo. "
								+ vmInfo.event_date);

						vmInfo.event_type_name = voicemail_event_name;
						vmInfo.event_type_image = icon_voicemail_24;
						vmInfo.event_type = EventType.VVM_UPDATE;
						vmInfo.contacts_id = NotificationDBHelper.getContactId(
								context, vmInfo.evnet_number);

						vmInfo.evnet_number_type = NotificationDBHelper
								.getNumberTypeByMap(context,
										vmInfo.evnet_number, numberTypeMap);
						LogHelper.i(TAG, "getVoiceMailInfo. type: "
								+ vmInfo.evnet_number_type);

						try {
							vmInfo.event_mmssubject_smscontent = c.getInt(c
									.getColumnIndex("length")) + " secs";
						} catch (Exception e) {
							LogHelper.e(TAG, "getVoiceMailInfo. ", e);
						}

						LogHelper.d(TAG, "getVoiceMailInfo. length: "
								+ vmInfo.event_mmssubject_smscontent);

						if (vmInfo.contacts_id != null) {
							vmInfo.contacts_image = NotificationDBHelper
									.getContactPhotoByContactId(context,
											vmInfo.contacts_id, contactPhotoMap);
							vmInfo.phoneNumberCount = NotificationDBHelper
									.getContactNumberCountByMap(context,
											vmInfo.contacts_id, numberCountMap);
							vmInfo.isInContacts = true;
							vmInfo.evnet_name = NotificationDBHelper
									.getDisplayNameByMap(context,
											vmInfo.contacts_id,
											contactDisplayNameMap);
							vmInfo.isVip = VipUtils.isVip(context,
									vmInfo.contacts_id);
						}
						voicemailEvents.add(vmInfo);
						c.moveToNext();
					}
					c.close();
				}
			} catch (Exception e) {
				LogHelper.e(TAG, "getVoiceMailInfo. ", e);
			} finally {
				if (c != null) {
					c.close();
				}
			}
		}
		return voicemailEvents;
	}

	public static boolean updateVVMStatusByIds(Context context, String[] ids) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_STATUS, 2);
		int count;
		try {
			// String where = " ";
			// for (int i = 0; i < ids.length; i++) {
			// if (" ".equals(where)) {
			// where = where + " _id=? ";
			// } else {
			// where = where + " or _id=? ";
			// }
			// }
			// update vvm_msg set status=2 where _id in(1,2,3);
			StringBuffer sb = new StringBuffer("_id in(");
			for (int i = 0; i < ids.length; i++) {
				sb.append(ids[i]).append(",");
			}
			String where = sb.substring(0, sb.length() - 1);
			where += ") ";

			count = context.getContentResolver().update(URI_VOICE_MAIL, values,
					where, null);
			LogHelper.d(
					"VVM",
					"##################updateVVMStatusByIds where is: " + where
							+ ",update count is: " + count
							+ ",status set to : "
							+ values.getAsString(COLUMN_STATUS));

			printVoicemailStatus(context);
		} catch (Exception e) {
			LogHelper.e(TAG, "updateVVMStatusByIds. ", e);
			return false;
		}
		if (count != 0) {
			return true;
		}
		return false;
	}

	// add by gaoge 2011-09-15
	public static void printVoicemailStatus(Context context) {
		StringBuffer sb = new StringBuffer();
		Cursor cursor = null;
		try {
			cursor = context.getContentResolver().query(URI_VOICE_MAIL,
					new String[] { "_id,status" }, null, null, null);
			if (null != cursor) {
				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					String _id = cursor.getString(cursor.getColumnIndex("_id"));
					String status = cursor.getString(cursor
							.getColumnIndex("status"));
					sb.append("_id: ").append(_id).append(",status: ")
							.append(status).append("\n");
					cursor.moveToNext();
				}
			}
		} catch (Exception e) {
			// There is no vvm provider.
			// ignore.
		} finally {
			if (null != cursor) {
				cursor.close();
			}
		}
		LogHelper.d(
				TAG,
				"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ [_id,status]  is: "
						+ sb.toString());

	}
}
